package com.zyzd.baseprojectofvolly;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMFileMessageBody;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMLocationMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;
import com.hyphenate.chat.EMNormalFileMessageBody;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.EMVideoMessageBody;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.zyzd.baseprojectofvolly.base.activity.BaseNetActivity;
import com.zyzd.baseprojectofvolly.bean.local.ApiChatMessage;
import com.zyzd.baseprojectofvolly.bean.local.ApiMessageBody;
import com.zyzd.baseprojectofvolly.bean.remote.ApiResultBean;
import com.zyzd.baseprojectofvolly.chat.DemoHelper;
import com.zyzd.baseprojectofvolly.chat.activity.ChatActivity;
import com.zyzd.baseprojectofvolly.chat.db.DemoDBManager;
import com.zyzd.baseprojectofvolly.chat.db.InviteMessgeDao;
import com.zyzd.baseprojectofvolly.chat.db.UserDao;
import com.zyzd.baseprojectofvolly.utils.FileUtils;
import com.zyzd.commontools.log.TLog;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

public class MainActivity extends BaseNetActivity<ArrayList<String>> {
    @Bind(R.id.btn_tochat)
    Button btnTochat;
    @Bind(R.id.btn_pull)
    Button btnPull;
    @Bind(R.id.btn_get)
    Button btnGet;


    public static String avatar = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3588773685,3085734296&fm=26&gp=0.jpg";
    public static String nickname = "斬阳";

//    private String tochatName = "3b8900f72c6a421aa795026202b2068a";
    private String tochatName = "0cd2085f84e74afa9d32f65d178a1a16";
    final String  currentUsername = "ecffaf477a474d6e90457cecc9233644";

    final String currentPassword = "123456";


    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        hxlogin();
    }

    private void hxlogin() {
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            showToast(getString(R.string.network_isnot_available));
            return;
        } else {
            method();
        }

        DemoDBManager.getInstance().closeDB();

        DemoHelper.getInstance().setCurrentUserName(currentUsername);

        DemoHelper.getInstance().getUserInfo(currentUsername).setAvatar(avatar);
        DemoHelper.getInstance().getUserInfo(currentUsername).setNickname(nickname);

        EMClient.getInstance().login(currentUsername, currentPassword, mEmCallBack);
        EMClient.getInstance().chatManager().addMessageListener(messageListener);

    }

    /**
     * 环信登录回调
     */
    private EMCallBack mEmCallBack = new EMCallBack() {

        @Override
        public void onSuccess() {
            TLog.d("zyzd", "MainActivity>>onSuccess--> 登录环信成功");

            // ** manually load all local groups and conversation
            EMClient.getInstance().groupManager().loadAllGroups();
            EMClient.getInstance().chatManager().loadAllConversations();
            // update current user's display name for APNs
//            PersonInfoBean userInfo = UserHelper.getUserInfo();

            // get user's info (this should be get from App's server or 3rd party service)

            boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(nickname);
            EMClient.getInstance().updateCurrentUserNick(avatar);
            if (!updatenick) {
                TLog.e("zyzd", "update current user nick fail");
            }
            EaseUser currentUserInfo = DemoHelper.getInstance().getUserProfileManager().getCurrentUserInfo();
            currentUserInfo.setNickname(nickname);
            currentUserInfo.setAvatar(avatar);

            method();

        }

        @Override
        public void onProgress(int progress, String status) {
            Log.d("zyzd", "login: onProgress");
        }

        @Override
        public void onError(final int code, final String message) {
            Log.d("zyzd", "login: onError: " + code + " " + message);
        }
    };

    private void method() {
        new InviteMessgeDao(getApplicationContext());//初始化留言消息的数据库对象
        new UserDao(getApplicationContext());//初始化用户数据库对象
    }

    @OnClick({R.id.btn_tochat, R.id.btn_pull, R.id.btn_get})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_pull:
                pull();
                break;
            case R.id.btn_tochat:
                openChatActivity(this, tochatName);
                break;
            case R.id.btn_get:
                break;
        }

    }

    /**
     * 打开聊天界面
     */
    public static void openChatActivity(Context context, String userId) {
        context.startActivity(new Intent(context, ChatActivity.class).putExtra("userId", userId));
    }

    private EMMessageListener messageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> list) {

            if (list == null)
                return;
            for (EMMessage emMessage : list) {
                try {
                    ApiChatMessage apiChatMessage = new ApiChatMessage();

                    String chat_type = "chat";
                    if (EMMessage.ChatType.ChatRoom == emMessage.getChatType()) {
                        chat_type = "chatroom";
                    } else if (EMMessage.ChatType.GroupChat == emMessage.getChatType()) {
                        chat_type = "groupchat";
                    }
                    apiChatMessage.setChat_type(chat_type);
                    apiChatMessage.setDirection("outgoing");
                    apiChatMessage.setFrom(emMessage.getFrom());
                    apiChatMessage.setMsg_id(emMessage.getMsgId());
//                  apiChatMessage.setPayload(emMessage.getBody());
                    apiChatMessage.setTimestamp(emMessage.getMsgTime());
                    apiChatMessage.setTo(emMessage.getTo());

                    ApiMessageBody apiMessageBody = new ApiMessageBody();
                    fillBodies(emMessage, apiMessageBody);
                    apiChatMessage.getPayload().getBodies().add(apiMessageBody);

                    apiChatMessage.getPayload().setFrom(emMessage.getFrom());
                    apiChatMessage.getPayload().setTo(emMessage.getTo());

                    //额外字段
                    apiChatMessage.getPayload().getExt().setNickname(emMessage.getStringAttribute(Constant.MESSAGE_ATTR_NICKNAME, ""));
                    apiChatMessage.getPayload().getExt().setAvater(emMessage.getStringAttribute(Constant.MESSAGE_ATTR_AVATER, ""));
                    apiChatMessage.getPayload().getExt().setType(emMessage.getIntAttribute(Constant.MESSAGE_ATTR_TYPE, 2));//根据端来确定

                    push(new Gson().toJson(apiChatMessage));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> list) {

        }

        @Override
        public void onMessageRead(List<EMMessage> list) {

        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {

        }

        @Override
        public void onMessageChanged(EMMessage emMessage, Object o) {

        }
    };

    private void fillBodies(EMMessage emMessage, ApiMessageBody apiMessageBody) {
        EMMessageBody body = emMessage.getBody();
        if (EMMessage.Type.TXT == emMessage.getType()) {
            EMTextMessageBody emTextMessageBody = (EMTextMessageBody) body;
            apiMessageBody.setMsg(emTextMessageBody.getMessage());
            apiMessageBody.setType("txt");

        } else if (EMMessage.Type.IMAGE == emMessage.getType()) {
            EMImageMessageBody emImageMessageBody = (EMImageMessageBody) body;
            //                    apiMessageBody.setFile_length();
            apiMessageBody.setFilename(emImageMessageBody.getFileName());
            apiMessageBody.setSecret(emImageMessageBody.getSecret());
            apiMessageBody.getSize().setWidth(emImageMessageBody.getWidth());
            apiMessageBody.getSize().setHeight(emImageMessageBody.getHeight());
            apiMessageBody.setUrl(emImageMessageBody.getRemoteUrl());
            apiMessageBody.setType("img");

        } else if (EMMessage.Type.LOCATION == emMessage.getType()) {
            EMLocationMessageBody emLocationMessageBody = (EMLocationMessageBody) body;
            apiMessageBody.setAddr(emLocationMessageBody.getAddress());
            apiMessageBody.setLat(emLocationMessageBody.getLatitude());
            apiMessageBody.setLng(emLocationMessageBody.getLongitude());
            apiMessageBody.setType("loc");

        } else if (EMMessage.Type.VOICE == emMessage.getType()) {
            EMVoiceMessageBody emVoiceMessageBody = (EMVoiceMessageBody) body;
            emVoiceMessageBody.getLocalUrl();
            //apiMessageBody.setFile_length(emVoiceMessageBody.);
            apiMessageBody.setFilename(emVoiceMessageBody.getFileName());
            apiMessageBody.setLength(emVoiceMessageBody.getLength());
            apiMessageBody.setSecret(emVoiceMessageBody.getSecret());
            apiMessageBody.setUrl(emVoiceMessageBody.getRemoteUrl());
            apiMessageBody.setType("audio");

        } else if (EMMessage.Type.VIDEO == emMessage.getType()) {
            EMVideoMessageBody emVideoMessageBody = (EMVideoMessageBody) body;
            apiMessageBody.setFile_length(emVideoMessageBody.getVideoFileLength());
            apiMessageBody.setFilename(emVideoMessageBody.getFileName());
            apiMessageBody.setLength(emVideoMessageBody.getDuration());
            apiMessageBody.setSecret(emVideoMessageBody.getSecret());
            //apiMessageBody.getSize().setHeight(emVideoMessageBody.);
            apiMessageBody.setThumb(emVideoMessageBody.getThumbnailUrl());
            apiMessageBody.setThumb_secret(emVideoMessageBody.getThumbnailSecret());
            apiMessageBody.setUrl(emVideoMessageBody.getRemoteUrl());
            apiMessageBody.setType("video");

        } else if (EMMessage.Type.FILE == emMessage.getType()) {

            EMFileMessageBody emFileMessageBody = (EMFileMessageBody) body;

            //apiMessageBody.setFile_length();
            apiMessageBody.setFilename(emFileMessageBody.getFileName());
            apiMessageBody.setSecret(emFileMessageBody.getSecret());
            apiMessageBody.setType("file");
            apiMessageBody.setUrl(emFileMessageBody.getRemoteUrl());

        } /*else if (EMMessage.Type.CMD == emMessage.getType()) {

        }*/
    }

    @Override
    protected Type getType(String tag) {
        return new TypeToken<ApiResultBean<ArrayList<String>>>() {
        }.getType();
    }

    @Override
    protected void parseData(ArrayList<String> data, String tag) {
        ArrayList<EMMessage> emMessages = new ArrayList<>();
        for (String msgStr : data) {

            ApiChatMessage apiChatMessage = new Gson().fromJson(msgStr, new TypeToken<ApiChatMessage>() {
            }.getType());

            parseEMMessage(emMessages, apiChatMessage);
        }
        EMClient.getInstance().chatManager().importMessages(emMessages);
    }

    private void parseEMMessage(ArrayList<EMMessage> emMessages, ApiChatMessage apiChatMessage) {
        EMMessage emMessage = null;
        if (apiChatMessage.getPayload().getBodies().size() == 0) {
            return;
        }

        EMMessage.Type type = getEMMessageType(apiChatMessage.getPayload().getBodies().get(0).getType());
        if (apiChatMessage.getFrom().equals(currentUsername)) {
            //自己发送的
            emMessage = EMMessage.createSendMessage(type);
            emMessage.setStatus(EMMessage.Status.SUCCESS);
        } else if (apiChatMessage.getTo().equals(currentUsername)) {
            //自己接收的
            emMessage = EMMessage.createReceiveMessage(type);
        } else {
            return;
        }
        emMessage.setMsgId(apiChatMessage.getMsg_id());
        emMessage.setMsgTime(apiChatMessage.getTimestamp());
        emMessage.setTo(apiChatMessage.getTo());
        emMessage.setFrom(apiChatMessage.getFrom());

        switch (apiChatMessage.getChat_type()) {
            case "chatroom":
                emMessage.setChatType(EMMessage.ChatType.ChatRoom);
                break;
            case "groupchat":
                emMessage.setChatType(EMMessage.ChatType.GroupChat);
                break;
            default:
                emMessage.setChatType(EMMessage.ChatType.Chat);
                break;
        }

        for (ApiMessageBody body : apiChatMessage.getPayload().getBodies()) {

            switch (body.getType()) {
                case "txt":
                    emMessage.addBody(new EMTextMessageBody(body.getMsg()));
                    break;
                case "img":
                    EMImageMessageBody emImageMessageBody = new EMImageMessageBody(getHxFile(body.getUrl()));
                    emImageMessageBody.setFileName(body.getFilename());
                    emImageMessageBody.setSecret(body.getSecret());
                    emImageMessageBody.setRemoteUrl(body.getUrl());
                    emMessage.addBody(emImageMessageBody);
                    break;
                case "loc":
                    emMessage.addBody(new EMLocationMessageBody(body.getAddr(), body.getLat(), body.getLng()));
                    break;
                case "audio":
                    EMVoiceMessageBody emVoiceMessageBody = new EMVoiceMessageBody(getHxFile(body.getUrl()), body.getLength());
                    emVoiceMessageBody.setFileName(body.getFilename());
                    emVoiceMessageBody.setSecret(body.getSecret());
                    emVoiceMessageBody.setRemoteUrl(body.getUrl());
                    emMessage.addBody(emVoiceMessageBody);
                    break;
                case "video":
                    String videoPath = getHxFile(body.getUrl()).getAbsolutePath();
                    String thumbPath = getHxFile(body.getThumb()).getAbsolutePath();
                    EMVideoMessageBody emVideoMessageBody = new EMVideoMessageBody(videoPath, thumbPath, body.getLength(), body.getFile_length());
                    //emVideoMessageBody.setVideoFileLength(body.getFile_length());
                    emVideoMessageBody.setFileName(body.getFilename());
                    emVideoMessageBody.setSecret(body.getSecret());
                    emVideoMessageBody.setThumbnailSecret(body.getThumb_secret());
                    emVideoMessageBody.setThumbnailUrl(body.getThumb());
                    emVideoMessageBody.setRemoteUrl(body.getUrl());
                    //emVideoMessageBody.setLocalUrl(videoFile.getAbsolutePath());

                    emMessage.addBody(emVideoMessageBody);
                    break;
                case "imageFile":
                    EMFileMessageBody emFileMessageBody = new EMNormalFileMessageBody(getHxFile(body.getUrl()));
                    emFileMessageBody.setFileName(body.getFilename());
                    emFileMessageBody.setSecret(body.getSecret());
                    emFileMessageBody.setRemoteUrl(body.getUrl());
                    emMessage.addBody(emFileMessageBody);
                    break;
            }
        }
        emMessages.add(emMessage);
    }

    public File getHxFile(String remoteUrl) {
        return FileUtils.getHxFile(getApplicationContext(), currentUsername, tochatName, remoteUrl);
    }

    public void push(String s) {
        Map<String, String> params = new HashMap<>();
        params.put("content", s);
        requestDataByPost("http://192.168.0.101:8082/message/upload", params, "push");
        TLog.d("zyzd", "MainActivity>>push--> " + s);
    }

    /**
     * 1.考虑是接收消息还是发送消息
     * 2.考虑是消息类型
     */
    public void pull() {
        Map<String, String> params = new HashMap<>();
        params.put("from", tochatName);
        params.put("to", currentUsername);
        params.put("timestamp", System.currentTimeMillis() + "");
        params.put("page", "0");
        params.put("size", "10");
        requestDataByPost("http://192.168.0.101:8082/message/list", params);
    }

    @NonNull
    private EMMessage.Type getEMMessageType(String type) {
        switch (type) {
            case "img":
                return EMMessage.Type.IMAGE;
            case "loc":
                return EMMessage.Type.LOCATION;
            case "audio":
                return EMMessage.Type.VOICE;
            case "video":
                return EMMessage.Type.VIDEO;
            case "file":
                return EMMessage.Type.FILE;
            default:
                return EMMessage.Type.TXT;
        }
    }
}
